package com.czc.mvc.config;

import com.czc.constant.CrowdConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
@EnableWebSecurity //启用web环境下权限控制功能
//启用全局方法权限控制功能 并设置prePostEnabled=true 保证@PreAuthorize、@PreFilter。。。几个注解生效
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebAppSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    /*
    在这里声明无法在XXservice中装配
    @Bean
    public BCryptPasswordEncoder getPasswordEncoder() {
        return  new BCryptPasswordEncoder();
    }*/

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
       /* //临时使用内存版登录的模式
        auth.inMemoryAuthentication()
                .withUser("tom")
                .password("123123")
                .roles("admin");*/

       auth.userDetailsService(userDetailsService)
               .passwordEncoder(passwordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests() //对请求进行授权
                .antMatchers("/admin/to/login/page.html")
                .permitAll()
                .antMatchers("/bootstrap/**")
                .permitAll()
                .antMatchers("/crowd/**")
                .permitAll()
                .antMatchers("/css/**")
                .permitAll()
                .antMatchers("/fonts/**")
                .permitAll()
                .antMatchers("/img/**")
                .permitAll()
                .antMatchers("/jquery/**")
                .permitAll()
                .antMatchers("/layer/**")
                .permitAll()
                .antMatchers("/script/**")
                .permitAll()
                .antMatchers("/WEB-INF/**")
                .permitAll()
                .antMatchers("/ztree/**")
                .permitAll()
                .antMatchers("/admin/get/page.html") //针对分页显示Admin数据设定访问控制
                //.hasRole("经理")  //要求具备经理的角色
                .access("hasRole('经理') OR hasAuthority('user:get')")
                .anyRequest()    //其他任意的请求
                .authenticated()  //认证后访问
                .and()
                .exceptionHandling()
                .accessDeniedHandler(new AccessDeniedHandler() {
                    @Override
                    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
                        System.out.println(e+"=================================");
                        httpServletRequest.setAttribute("exception",new Exception(CrowdConstant.MESSAGE_ACCESS_DENIED));
                        httpServletRequest.getRequestDispatcher("/WEB-INF/system-error.jsp").forward(httpServletRequest,httpServletResponse);
                    }
                })
                .and()
                .csrf()
                .disable()
                .formLogin()  //开启表单登录的功能
                .loginPage("/admin/to/login/page.html") //指定登录的页面
                .loginProcessingUrl("/security/do/login.html")  //指定处理登录请求的地址
                .defaultSuccessUrl("/admin/to/main/page.html") //指定登录成功后跳转的页面
                .usernameParameter("loginAcct") //帐号的请求参数名称
                .passwordParameter("userPswd") //密码的请求参数名称
                .and()
                .logout()     //开启退出登录功能
                .logoutUrl("/seucrity/do/logout.html")          //指定退出登录的地址
                .logoutSuccessUrl("/admin/to/login/page.html")  //指定退出成功以后跳转的地址
                ;

    }
}
;